from typing import Optional, Union

from fastapi import FastAPI
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings
from afast_core.core_libs.starsessions import CookieStore, AsyncRedisStore, InMemoryStore, SessionMiddleware, \
    SessionAutoloadMiddleware


class SessionPluginClient(BasePlugin):
    '''
    使用示例：
    # 更多使用 开源查看官网地址：https://github.com/alex-oleshkevich/starsessions
    seck = SessionPluginClient(core_app=core_app, configs=SessionPluginClient.SessionConfig(
        is_auto_load=True
    ))
    # 使用装饰定义路由端点函数，并定义路由路径以及Path路径参数
    @core_app.get("/stream")
    def stream(request:Request):
        # 写入
        request.session["session_code"] = '123456'
        # 读取（另一个接口读取）
        # cyrewct_code = request.session["session_code"]
        return 'ok'
    '''

    # 设置插件默认的参数信息
    name = 'Session插件'

    class SessionConfig(Settings):
        # 实例化的Session插件的秘钥
        session_store: Union[CookieStore, AsyncRedisStore, InMemoryStore] = CookieStore(secret_key='kTd5NsCsaj52TzHb')
        # 只是只允许https读取
        cookie_https_only: bool = False
        # 会话生存时间
        lifetime: int = 3600 * 24 * 14
        # 是否自动加载
        is_auto_load: bool = True
        # 是否滚地会话时效续期
        is_rolling: bool = False

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        if self.settings.is_auto_load:
            app.add_middleware(SessionAutoloadMiddleware)
        # SessionMiddleware, store = session_store, lifetime = 3600 * 24 * 14
        app.add_middleware(SessionMiddleware, store=self.settings.session_store,
                           cookie_https_only=self.settings.cookie_https_only,
                           lifetime=self.settings.lifetime, rolling=self.settings.is_rolling)
